package priv.wangy.micro.common.dstb.lock;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import priv.wangy.micro.common.config.appnode.AppNodeConfig;
import priv.wangy.micro.common.config.appnode.AppNodeProperties;

import java.util.Collections;
import java.util.Objects;

/**
 * @author zhangjq
 * @since 2023-10-17
 */
@Component
public class DistributedLockUtil {

    private final AppNodeProperties properties;

    private final StringRedisTemplate redisTemplate;

    public DistributedLockUtil(AppNodeConfig config, StringRedisTemplate redisTemplate) {
        this.properties = config.getAppNodeProperties();
        this.redisTemplate = redisTemplate;
    }

    /**
     * 上锁
     *
     * @return boolean
     * @author zhangjq
     * @since 2023-10-17
     */
    public boolean lock(String key, String value, Long expire) {
        String luaScript = "if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then return redis.call('expire', KEYS[1], ARGV[2]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(key),
                String.format("%02d-%02d-%s", properties.getAppIndex(), properties.getNodeIndex(), value), String.valueOf(expire));
        return !Objects.isNull(result) && result.equals(1L);
    }

    /**
     * 解锁
     *
     * @author zhangjq
     * @since 2023-10-17
     */
    public void unlock(String key, String value) {
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(key),
                String.format("%02d-%02d-%s", properties.getAppIndex(), properties.getNodeIndex(), value));
    }
}
